var Config = require('config');
var queueConf = Config.get('message_queue');
var DEFAULT_QUEUE = 'amqp://' + queueConf.username + ':' + queueConf.password + '@' + queueConf.server + '/' + queueConf.virtual_hose;

var channelWrapper;

var crypto = require('crypto');

const EventEmitter = require('events');
var emitter = new EventEmitter();
function onRawData(data) {
    // TODO calculate the hash value of this package
    var pkg = {
        station: Config.get('station').id,
        data: data.toString('base64'),
        length: data.length,
        fetched_at: (new Date()).toISOString()
    }
    emitter.emit('new_pkg', pkg);
    // TODO save to log file
    // TODO try upload with logstash
}

emitter.on('new_pkg', function (pkg) {
    if (channelWrapper) {
        channelWrapper.sendToQueue(queueConf.name, pkg)
            .then(function () {
                console.log('sent');
            }, function (err) {
                console.log('failed');
                // TODO deal with these packages
            });
    }
});

function setupSerialPort() {
    var fs = require('fs');
    var StreamBrake = require('streambrake');
    var stream = fs.createReadStream(__dirname + '/rover.txt').pipe(new StreamBrake(100));
    stream.on("data", onRawData);
    stream.on("close", function () {
        // TODO cleanup: close log file, close
    })
}
setupSerialPort();

function setupMQ() {
    var amqp = require('amqp-connection-manager');
    var connection = amqp.connect([], {
        findServers: function (callback) {
            console.log('message queue server=' + DEFAULT_QUEUE);
            return Promise.resolve(DEFAULT_QUEUE);
        }
    });
    channelWrapper = connection.createChannel({
        json: true,
        setup: function (channel) {
            console.log('connected');
            return channel.assertQueue(queueConf.name, {durable: false})
        }
    });
}
setupMQ();

